/*
 * Copyright 2010 Mttang.com All right reserved. This software is the
 * confidential and proprietary information of Mttang.com ("Confidential
 * Information"). You shall not disclose such Confidential Information and shall
 * use it only in accordance with the terms of the license agreement you entered
 * into with Mttang.com.
 */
package com.mttang.sys.web.controller;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.util.Random;

import javax.imageio.ImageIO;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.ModelAndView;
import com.mttang.framework.core.web.controller.BaseDispatcherSimpleFormController;
import com.mttang.util.BASE64Encoder;
import com.mttang.util.Tools;

/**
 * 生成验证码图片请求
 * 
 * @author 
 * 
 */
public class ImageController extends BaseDispatcherSimpleFormController {
	protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response)
			throws Exception {

		response.setContentType("image/jpeg");
		// 在内存中创建图象
		int width = 60, height = 20;
		BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
		// 获取图形上下文
		Graphics g = image.getGraphics();

		// 生成随机类
		Random random = new Random();
		// 设定背景色
		g.setColor(Tools.getRandColor(200, 250));
		g.fillRect(0, 0, width, height);
		// 设定字体
		g.setFont(new Font("Times New Roman", Font.PLAIN, 18));

		// 随机产生155条干扰线，使图象中的认证码不易被其它程序探测到
		g.setColor(Tools.getRandColor(160, 200));
		for (int i = 0; i < 155; i++) {
			int x = random.nextInt(width);
			int y = random.nextInt(height);
			int xl = random.nextInt(12);
			int yl = random.nextInt(12);
			g.drawLine(x, y, x + xl, y + yl);
		}

		// 取随机产生的认证码(4位数字)
		long time = System.currentTimeMillis();
		String stime = Long.toHexString(time);
		Cookie cookie = new Cookie("VERIFY_KEY", stime);
		//cookie.setDomain("localhost");
		//cookie.setPath("/");
		response.addCookie(cookie);
		BASE64Encoder encode = new BASE64Encoder();
		String encodeStr = encode.encode(stime.getBytes());
		StringBuilder yzm = new StringBuilder("");
		for (int i = encodeStr.length() - 1; i >= 0; i--) {
			if (Tools.isNumberOrLetter(encodeStr.charAt(i))) {
				yzm.append(encodeStr.charAt(i));
			}

			if (yzm.length() == 4) {
				break;
			}
		}

		for (int i = 0; i < 4; i++) {
			String rand = String.valueOf(yzm.charAt(i));
			// 将认证码显示到图象中
			g.setColor(new Color(20 + random.nextInt(110), 20 + random.nextInt(110), 20 + random.nextInt(110)));// 调用函数出来的颜色相同，可能是因为种子太接近，所以只能直接生成
			g.drawString(rand, 13 * i + 6, 16);
		}
		g.dispose();

		// 输出图象到页面
		ImageIO.write(image, "JPEG", response.getOutputStream());

		return null;
	}
}
